import { Button , Form,
  message,Input } from 'antd';
import { Link } from 'umi';
import React from 'react';
import { RouteChildrenProps } from 'react-router';
import styles from '../user/login/style.less';
import request from "@/utils/request";
import router from 'umi/router';

const UpdatePassword: React.FC<RouteChildrenProps> = () => {
  const FormItem = Form.Item;
  const formLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  const formRef = React.createRef();
  const GetQueryString = (name) => {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return unescape(r[2]);
    }
    return null;
  }
  const handleSubmit = async (values: object) => {
    let {validateFields} =  formRef.current;
    validateFields().then(values=>{
      console.log(values);
      if(values.password != values.twopassword){
        message.error("两次密码不一样");
        return
      }
      request.put('/api/emailpassword', {
        params: {
          password:values.password,
          token:GetQueryString("token")
        }
      }).then((result:Object)=>{
        console.log(result)
        if (result.data.success == true) {
          message.info("修改成功");
          router.push('/user/login');
        }else{
          message.info("修改失败");
        }
        return true;
      })
    })
  };
  return (
    <div className={styles.main}>
      <h2 style={{textAlign:'center',marginBottom:20}}>修改密码</h2>
      <Form onFinish={handleSubmit}
            {...formLayout}
            ref={formRef}>
        <Form.Item label="密码" hasFeedback name="password"
                   rules={[
                     {
                       required: true,
                       message: "Please input your password!"
                     },
                   ]}>
          <Input.Password/>
        </Form.Item>
        <Form.Item label="确认密码" hasFeedback name="twopassword"
                   rules={[
                     {
                       required: true,
                       message: "Please input your password!"
                     },
                   ]}>
          <Input.Password/>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{marginLeft:93}}>
            修改密码
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default UpdatePassword;
